package logging

import (
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"os"
	"time"
)

type Level int

var (
	F *os.File

	DefaultPrefix      = ""
	DefaultCallerDepth = 2

	logger     *logrus.Logger
	logPrefix  = ""
	levelFlags = []string{"DEBUG", "INFO", "WARN", "ERROR", "FATAL"}
)

const (
	DEBUG Level = iota
	INFO
	WARNING
	ERROR
	FATAL
)

// Debug output logs at debug level
func Debug(f string, v ...interface{}) {
	logger.Debugf(f, v)
}

// Info output logs at info level
func Infof(f string, v ...interface{}) {
	logger.Infof(f, v)
}


// Info output logs at info level
func Info(v ...interface{}) {
	logger.Info(v)
}
// Warn output logs at warn level
func Warn(v ...interface{}) {
	logger.Warn(v)
}

// Error output logs at error level
func Error(v ...interface{}) {
	logger.Error(v)
}

// Fatal output logs at fatal level
func Fatal(v ...interface{}) {
	logger.Fatal(v)
}

func Setup() gin.HandlerFunc {

	//logFilePath := getLogFilePath()
	//logFileName := getLogFileName()

	//日志文件
	//fileName := path.Join(logFilePath, logFileName)

	//写入文件
	//src, err := os.OpenFile(fileName, os.O_APPEND|os.O_WRONLY, os.ModeAppend)
	//if err != nil {
	//	fmt.Println("err", err)
	//}

	//实例化
	logger = logrus.New()

	//设置输出
	logger.Out = os.Stdout

	//设置日志级别
	logger.SetLevel(logrus.DebugLevel)

	//设置日志格式
	logger.SetFormatter(&logrus.TextFormatter{})

	return func(c *gin.Context) {
		// 开始时间
		startTime := time.Now()

		// 处理请求
		c.Next()

		// 结束时间
		endTime := time.Now()

		// 执行时间
		latencyTime := endTime.Sub(startTime)

		// 请求方式
		reqMethod := c.Request.Method

		// 请求路由
		reqUri := c.Request.RequestURI

		// 状态码
		statusCode := c.Writer.Status()

		// 请求IP
		clientIP := c.ClientIP()

		// 日志格式
		logger.Infof("| %3d | %13v | %15s | %s | %s |",
			statusCode,
			latencyTime,
			clientIP,
			reqMethod,
			reqUri,
		)
	}
}
